package src;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Matias
 */
public class VentanaJuego extends javax.swing.JFrame {

    /**
     * Creates new form VentanaJuego
     * 
     */
	
	
    public VentanaJuego() {
    	this.setTitle("Linguo2 - The Empire Strinke Back on the Lost Ark of the Temple of Doom, in a New Hope");
        this.setIconImage(new ImageIcon(getClass().getResource("Derecha.png")).getImage());
    	initComponents();
        setBackground(Color.WHITE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        pap = new PapelMapa();
        	//iniciar juego
        	j=new Linguo2();
        	try {
        		j.cargarMapa("Nivel.txt");
        	} catch (ErrorEnCargarArchivo e) {
        		// TODO Auto-generated catch block
        		e.printStackTrace();
        	}
        	j.crearRobotMilita();
		
        pap.cargarMapa(j.getMapa());
        
        
        izquierda = new javax.swing.JButton();
        	izquierda.setIcon(new ImageIcon(getClass().getResource("girarIzq.png")));
        	OyenteIzquierda oi= new OyenteIzquierda();
        	izquierda.addActionListener(oi);
        	izquierda.addKeyListener( new java.awt.event.KeyAdapter() {
	          public void keyReleased(java.awt.event.KeyEvent evt) {
	            vKeyReleased(evt);
	          }});
        
        avanzar = new javax.swing.JButton();
        	avanzar.setIcon(new ImageIcon(getClass().getResource("avanzar.png")));
        	OyenteAvanzar oa=new OyenteAvanzar();
        	avanzar.addActionListener(oa);
        	avanzar.addKeyListener( new java.awt.event.KeyAdapter() {
    	          public void keyReleased(java.awt.event.KeyEvent evt) {
    	  	            vKeyReleased(evt);
    	  	          }});
    	        	
        
        derecha = new javax.swing.JButton();
        	derecha.setIcon(new ImageIcon(getClass().getResource("girarDer.png")));
        	OyenteDerecha ode=new OyenteDerecha();
        	derecha.addActionListener(ode);
        	derecha.addKeyListener( new java.awt.event.KeyAdapter() {
        		public void keyReleased(java.awt.event.KeyEvent evt) {
	  	            vKeyReleased(evt);
	  	          }});
	        	
        
        disparar = new javax.swing.JButton();
        	OyenteDisparar od= new OyenteDisparar();
        	disparar.addActionListener(od);
        	disparar.addKeyListener( new java.awt.event.KeyAdapter() {
  	          public void keyReleased(java.awt.event.KeyEvent evt) {
  	            vKeyReleased(evt);
  	          }});
        	
        iniciar = new javax.swing.JButton();
        	OyenteIniciar oiz= new OyenteIniciar();
        	iniciar.addActionListener(oiz);
        	iniciar.addKeyListener( new java.awt.event.KeyAdapter() {
    	          public void keyReleased(java.awt.event.KeyEvent evt) {
    	  	            vKeyReleased(evt);
    	  	          }});
    	        	
        /*reiniciar = new javax.swing.JButton();
        	OyenteReiniciar or= new OyenteReiniciar();
        	reiniciar.addActionListener(or);
        	reiniciar.addKeyListener( new java.awt.event.KeyAdapter() {
    	          public void keyReleased(java.awt.event.KeyEvent evt) {
    	  	            vKeyReleased(evt);
    	  	          }});*/
        	
        	reiniciar = new javax.swing.JButton();
        	OyenteRecolectar or= new OyenteRecolectar();
        	reiniciar.addActionListener(or);
        	reiniciar.addKeyListener( new java.awt.event.KeyAdapter() {
    	          public void keyReleased(java.awt.event.KeyEvent evt) {
    	  	            vKeyReleased(evt);
    	  	          }});
    	        	
        jLabel1 = new javax.swing.JLabel();
        puntaje = new javax.swing.JLabel();
        label2 = new javax.swing.JLabel();
        balas = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        combustible = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout papLayout = new javax.swing.GroupLayout(pap);
        pap.setLayout(papLayout);
        papLayout.setHorizontalGroup(
            papLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 501, Short.MAX_VALUE)
        );
        papLayout.setVerticalGroup(
            papLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 502, Short.MAX_VALUE)
        );

        izquierda.setText("");
        izquierda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                izquierdaActionPerformed(evt);
            }
        });

        avanzar.setText("");

        derecha.setText("");

        disparar.setText("Disparar");

        iniciar.setText("Iniciar");

        reiniciar.setText("Reiniciar");

        jLabel1.setText("Puntaje");
        jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        label2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        label2.setForeground(new java.awt.Color(51, 51, 51));
        label2.setText("Balas");
        label2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel5.setText("Combustible");
        jLabel5.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(izquierda)
                                .addGap(14, 14, 14)
                                .addComponent(avanzar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(derecha))
                            .addComponent(disparar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(iniciar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(reiniciar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(puntaje, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(balas, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(combustible, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(41, 41, 41)
                .addComponent(pap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(izquierda, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(avanzar, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(derecha, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(disparar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(puntaje, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(balas, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(combustible, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(iniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(reiniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(66, 66, 66))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        pap.setVisible(false);
    }// </editor-fold>

    private void izquierdaActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaJuego().setVisible(true);
            }
        });
    }
    public class OyenteIniciar implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
  			pap.setVisible(true);
  	       	actualizarEtiquetas();
  			
  		}
		
	
	   	
    }
    
    public class OyenteAvanzar implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			Posicion a=j.getMapa().getTerreno(j.getPosicionRobot()).getPosicion();
			Posicion p=j.avanzarRobot();
			if (p!=null){
				pap.moverRobot(j.getDireccionRobot(),a, p);
				pap.eliminarPremio(j.getMapa().getTerreno(p).getPosicion());
				}
			actualizarEtiquetas();
			
			if (j.gano())
				mostrarDialogoGanar();
				else
					if (j.perdio())
						mostrarDialogoPerder();
  			
  		}
    }

		private void actualizarEtiquetas() {
			puntaje.setText(""+j.getPuntaje());
			balas.setText(""+j.getBalas());
			combustible.setText(""+j.getCombustible());
			
		}
		
	
	   	
    
    
    public class OyenteIzquierda implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (j.girarRobotIzquierda()){
				pap.girar(j.getDireccionRobot());
			}
			actualizarEtiquetas();
			
			if (j.gano())
				mostrarDialogoGanar();
				else
					if (j.perdio())
						mostrarDialogoPerder();
			
  		}
		
	
	   	
    }
    
    public class OyenteDisparar implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			Posicion p=j.disparar()	;
			if (p!=null)	{
				
				pap.disparar(j.getDireccionRobot(),p);
				if (!(j.getMapa().getTerreno(p).hayObstaculo()))
					pap.eliminarObstaculo(p);
			}
			actualizarEtiquetas();
			/*JFileChooser elegir = new JFileChooser();
            int opcion = elegir.showOpenDialog(reiniciar);
       
            //Si presionamos el boton ABRIR en pathArchivo obtenemos el path del archivo
            if (opcion == JFileChooser.APPROVE_OPTION) {
                String pathArchivo = elegir.getSelectedFile().getPath(); //Obtiene path del archivo
                System.out.println(pathArchivo);
            }*/
			
		}
    	
    }
    
    public class OyenteReiniciar implements ActionListener{

  		@Override
  		public void actionPerformed(ActionEvent arg0) {
  			reiniciar();
  			
  			
  		}
      	
      }
    
    public void reiniciar(){
    	j.reiniciarNivel();
			int i=pap.getX();
			int y=pap.getY();
			pap.setVisible(false);
			pap=new PapelMapa();
			add(pap);
			pap.cargarMapa(j.getMapa());
	       	pap.setBounds(i,y,pap.getWidth(),pap.getHeight());
	       	pap.repaint();
	       	actualizarEtiquetas();
    }
    
    public class OyenteDerecha implements ActionListener{

  		@Override
  		public void actionPerformed(ActionEvent arg0) {
  			if (j.girarRobotDerecha()){
				pap.girar(j.getDireccionRobot());
			}
  			actualizarEtiquetas();
			
  			if (j.gano())
				mostrarDialogoGanar();
				else
					if (j.perdio())
						mostrarDialogoPerder();
  			
			
  			
  		}
      	
      }
    
    public class OyenteRecolectar implements ActionListener{
    	public void actionPerformed(ActionEvent arg0){
    		Posicion p=j.robotRecolectar();
    		if (p!=null){
    			pap.levantarColeccionable(p);
    		}
    		pap.recolectar(j.getDireccionRobot());
    	}
    }
    
private void vKeyReleased(java.awt.event.KeyEvent evt){
		
		//if (evt.getKeyCode()==KeyEvent.VK_ENTER){robot.setBounds(robot.getX()+2, robot.getY(), robot.getWidth(), robot.getHeight());}
		int co= evt.getKeyCode();
		
		switch (co){
			case KeyEvent.VK_LEFT:{
				
				if (j.girarRobotIzquierda()){
					pap.girar(j.getDireccionRobot());
				}
				actualizarEtiquetas();
				
				if (j.gano())
					mostrarDialogoGanar();
					else
						if (j.perdio())
							mostrarDialogoPerder();
				
				break;
			}
			
			case KeyEvent.VK_RIGHT:{
				
				if (j.girarRobotDerecha()){
					pap.girar(j.getDireccionRobot());
				}
				actualizarEtiquetas();
				
				if (j.gano())
					mostrarDialogoGanar();
					else
						if (j.perdio())
							mostrarDialogoPerder();
				
				break;
			}
			case KeyEvent.VK_UP:{
				Posicion a=j.getMapa().getTerreno(j.getPosicionRobot()).getPosicion();
				Posicion p=j.avanzarRobot();
				if (p!=null){
					
					pap.moverRobot(j.getDireccionRobot(),a,p);
					pap.eliminarPremio(j.getMapa().getTerreno(p).getPosicion());
					}
				actualizarEtiquetas();
				
				if (j.gano())
					mostrarDialogoGanar();
					else
						if (j.perdio())
							mostrarDialogoPerder();
						
				
				break;
			}
			case KeyEvent.VK_D:{
				Posicion p=j.disparar()	;
					if (p!=null)	{
						pap.disparar(j.getDireccionRobot(),p);
						if (!(j.getMapa().getTerreno(p).hayObstaculo()))
							pap.eliminarObstaculo(p);
					}
					actualizarEtiquetas();
				break;
			}
			
			}
		
		}
    
    
    
    
    
    
    private void mostrarDialogoPerder() {

    	JOptionPane.showMessageDialog(
    			   null,
    			   "Ha perdido","Perdiste",JOptionPane.ERROR_MESSAGE);
    	reiniciar();
	
}

	private void mostrarDialogoGanar() {
	
    	JOptionPane.showMessageDialog(
    			   null,
    			   "Felicitaciones ha ganado","Ganaste",JOptionPane.INFORMATION_MESSAGE);
    	reiniciar();
}






	// Variables declaration - do not modify
    private javax.swing.JButton avanzar;
    private javax.swing.JLabel balas;
    private javax.swing.JLabel combustible;
    private javax.swing.JButton derecha;
    private javax.swing.JButton disparar;
    private javax.swing.JButton iniciar;
    private javax.swing.JButton izquierda;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel label2;
    private javax.swing.JLabel puntaje;
    private javax.swing.JButton reiniciar;
    private PapelMapa pap;
    private Linguo2 j;
    // End of variables declaration
}
